﻿# encoding: UTF-8
import pandas, datetime
from strategy_platform.api import (submit_order,query_order,cancel_order, query_position,query_commodity_info,query_credit_fund_info, query_account)


def get_cash_credit(): # must return two positives
	try:
		account = query_credit_fund_info(g['acct_type'], g['acct'])
		if account is None:
			log.error("query_my_acct: can not find the credit account")  
		log.info("credit info is : 现金:{}, 股票市值:{}, 担保资产:{}, 融资可用额度:{}, totalDebit:{}".format(account.fundAsset,account.marketValue,account.assureAsset,account.finEnableQuota,account.totalDebit))  #TotalDebit是正数
		return account.fundAsset, account.totalDebit, account.marketValue
	except Exception as e:   
		log.exception(e)

def get_cash_():
	account = query_account(g['acct_type'], g['acct'])
	if account is None:   
		log.error("can not find the account")   
		return  
	log.info("account: [moneyType:{}, fundAcct:{}, currentBalance:{}, enabledBalance:{}]".format(account.moneyType, account.fundAcct, account.currentBalance,account.enabledBalance))       	
	

def on_init(argument_dict):
	global g
	g = {}
	g['acct_type']   = "C" #"SHHTSC" 
	g['acct']        = "8009180103" #"2497312" #	#"567543"	
	for k, v in argument_dict.items():
		g[k] = v
	log.info(g)
	
	cash, debit, stock = get_cash_()
	pos_list = query_position(g['acct_type'], g['acct'])
	eod = [{'code': 'CASH', 'qty': cash-debit}]
	if pos_list != None:
		for pos_obj in pos_list:
			eod.append({'code': pos_obj.symbol, 'qty':  pos_obj.currentQty})
	eod = pandas.DataFrame(eod)
	eod = eod[eod.qty!=0].copy()
	
	trade_date  = int(datetime.date.today().strftime('%Y%m%d'))
	filename    = 'D:/prod/sk001/eodpos/%d.csv'%trade_date #code, qty
	eod.to_csv(filename, index=0)
	log.info('eod written to %s, %d stocks, mktvalue = %dw [stock=%dw, cash=%dw]'%(filename, len(eod)-1, (cash-debit+stock)/1e4, stock/1e4, (cash-debit)/1e4))
	log.info(eod.head(3))
	